package net.soevar.common;

import net.soevar.database.hibernate.HibernateUtil;
import net.soevar.database.model.AthMenu;
import net.soevar.database.model.AthRole;
import net.soevar.database.model.AthRolePrivilage;
import net.soevar.database.model.AthUser;

import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

public class CommonPrivilages {

	public final static Integer READ = 0;
	public final static Integer CREATE = 1;
	public final static Integer UPDATE = 2;
	public final static Integer DELETE = 3;

	public static boolean checkPrevilages(Integer privilagesCode) {
		boolean result = false;
		AthMenu menu = Common.getCurrentMenu();
		System.out.println("Current menu = " + menu + ", privilagesCode = "
				+ privilagesCode);
		if (menu == null) {
			return result;
		}
		AthUser athuser = Common.getCurrentUser();
		AthRole athrole = athuser.getUserRole();

		Session session = HibernateUtil.currentSession();

		AthRolePrivilage rolePrivilage = (AthRolePrivilage) session
				.createCriteria(AthRolePrivilage.class)
				.add(Restrictions.eq("role", athrole))
				.add(Restrictions.eq("menu", menu)).setMaxResults(1)
				.uniqueResult();

		System.out.println("rolePrivilage = " + rolePrivilage + ", role = "
				+ athrole);

		if (rolePrivilage != null) {
			System.out.println("READ = " + rolePrivilage.getRead()
					+ ", CREATE = " + rolePrivilage.getCreate() + ", UPDATE = "
					+ rolePrivilage.getUpdate() + ", DELETE = "
					+ rolePrivilage.getDelete());
			if (READ.equals(privilagesCode)) {
				result = rolePrivilage.getRead().equals(1);
			} else if (CREATE.equals(privilagesCode)) {
				result = rolePrivilage.getCreate().equals(1);
			} else if (UPDATE.equals(privilagesCode)) {
				result = rolePrivilage.getUpdate().equals(1);
			} else if (DELETE.equals(privilagesCode)) {
				result = rolePrivilage.getDelete().equals(1);
			}
		}

		return result;
	}

}
